<?php
include_once($_SERVER['DOCUMENT_ROOT'] . "/php/dbi_connect.inc");
/*
 * The Procss Improvement Tracking Tool(PIT) was designed at 
 * SSC-Pac in order track compliance of center IPTs with
 * center System Engineering Management Plan.
 */

/**
 * Artifact handles artifact uploading. there is an old procedurel script that 
 * currently hadles this functionality. It is deprecated and uses mysql
 * this cass will based off using the new mysqi interface and should be used 
 * for all new development
 * This is radicly differnt by how much more modular it is and can be used in any 
 * project with minor adjustments
 * @author rpreston 2014.07.15
 */

/*
Superglobal $_File Properties
$_FILES["file"]["name"] - the name of the uploaded file
$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload
*/
class FileHandler 
{
    /***************************************************************************
     * Members
     ***************************************************************************/
    
    /***************
     * Holder for any error messages
     */
    private $resMsg;
    /***************
     * database connection object
     */
    private $db;

    /*****************
     * this requires an active connection to the db and project
     * @param db database connection
     */
    public function __construct(dbConnection $db) {
       $this->db        = $db;

    }
    
    /***************************************************************************
     * Functions
     ***************************************************************************/
    /********************
     * @param string the dom element name that we should search $_File for 
     * @param string target where we want to upload to 
     * @param
     * @return bool Returns false on failure Or True On Success
     * 
     * todo add an optional parameter to rename the file and add logic to decide whether to go with this name or the uploaded file name
     */
    public function uploadFile($fieldName,$base_path){
        if(!$this->isFileValid($_FILES[$fieldName]["name"])){
            return  false;
        }
        
        $target_path = $base_path ."/". basename( $_FILES[$fieldName]['name']);
        
        if(move_uploaded_file($_FILES[$fieldName]['tmp_name'], $target_path)) {       
           $this->resMsg = basename( $_FILES[$fieldName]['name'] )." Uploaded ";
           return  true;
        } 
        else {
            //this should be modified for future use
            $this->resMsg = "<div class='error-msg'>There was an error uploading "
                    . "the file. Possible reasons could be: <br>Authentication <br>"
                    . "File has too long a file name. File size over 10MB </div>";
            return false;
        }
    }

    /********************
     * @param string name of file that we are updating 
     * @param string the dome element field name of the the $_File
     * @param path where are uploading it to
     * @return bool Returns false on failure Or True On Success
     */
    public function updateFile($ogName,$fieldName,$base_path){

        if(!$this->deleteFile($ogName,$base_path)){
            return $this->resMsg;//fail
        }
        return $this->uploadFile($fieldName, $base_path);
    }
    
    /********************
     * @param string the dom element name that we should search $_File for 
     * @param string target where we want to upload to 
     * @return bool Returns false on failure Or True On Success
     * ../artifacts/".$_SESSION['thisProjectID'] ."/".$_POST['artifacts']
     * <div class='error-msg'>
     */
    public function deleteFile($fileName,$base_path){
        if( file_exists ( $base_path."/".$fileName )== true ){
            if(!unlink( $base_path ."/".$fileName) ){
                $this->resMsg = "<div class='error-msg'>Failed to delete file: " 
                              . $fileName."</div>";
            }
        }
        else{
             $this->resMsg =  "<div class='error-msg'>
                        Failed to unlink artifact. File does not exist. <br><br>
                        </div>";
            return false;
        }
        $this->resMsg ="<p>File Removed</p>";
        return true;
    }
    
    
   /********************
     * Returns false on failure Or String Confirmation On Success 
     * @param string this file
     * @return bool
     */
    private function isFileValid($thisFile){
        $fileExt= explode(".",$thisFile); 
        $ext    = strtolower(end($fileExt));
        switch($ext) {
            case "pdf":
            case "doc":
            case "docx":
            case "xls": 
            case "xlsx":
            case "xlsm":
            case "jpg":
            case "jpeg":
            case "tiff":
            case "png":
            case "txt":
            case "giff":
            case "pot":
            case "ppt":
            case "pptx":
            case "npp":
            case "zip":
            case "mpp":
                    return true;
            default:
                    $this->resMsg = "<div class='error-msg'> $ext is Not a Valid "
                    . "File Type please use the following:<br>pdf <br> doc<br>"
                    . "docx<br>zip <br>mpp<br>xls<br>xlsx<br>xlsm<br>jpg<br>"
                    . "jpeg<br>tiff<br> png<br>txt<br> giff<br> pot<br>ppt<br> "
                    . "pptx<br> npp<br></div> ";
                    return false;
        }
    }
    
    
    /**************************************************************************
     * Accessers-Mutators
     **************************************************************************/
    public function getResMsg(){
        return $this->resMsg;
    }
    
    /**************************************************************************/
}
